from django.conf import settings
from urllib.parse import parse_qs,urlencode
from urllib.request import urlopen
import json

class QQOauth(object):

    def get_url(self):

        base_url = 'https://graph.qq.com/oauth2.0/authorize?'

        state = '/'
        # 组织参数
        params = {
            'response_type': 'code',
            'client_id': settings.QQ_APP_ID,
            'redirect_uri': settings.QQ_REDIRECT_URL,
            'state': state,
            # 'scope':'get_user_info'
        }

        # 将query中的字典转换为url路径中的查询字符串
        auth_url = base_url + urlencode(params)

        return auth_url

    def get_token(self,code):


        # PC网站：https://graph.qq.com/oauth2.0/token
        # GET
        # grant_type      必须      授权类型，在本步骤中，此值为“authorization_code”。
        # client_id       必须      申请QQ登录成功后，分配给网站的appid。
        # client_secret   必须      申请QQ登录成功后，分配给网站的appkey。
        # code            必须      上一步返回的authorization
        # redirect_uri    必须      与上面一步中传入的redirect_uri保持一致。

        base_url = 'https://graph.qq.com/oauth2.0/token?'

        params = {
            'grant_type': 'authorization_code',
            'client_id': settings.QQ_APP_ID,
            'client_secret': settings.QQ_APP_KEY,
            'code': code,
            'redirect_uri': settings.QQ_REDIRECT_URL

        }

        token_url = base_url + urlencode(params)

        # 生成url需要自己请求
        response = urlopen(token_url)

        data = response.read().decode()

        # print(data)

        dict = parse_qs(data)

        # print(dict['access_token'])

        access_token = dict['access_token']

        token = access_token[0]

        return token

    def get_openid(self,access_token):

        # https://graph.qq.com/oauth2.0/me
        # GET
        # access_token        必须      在Step1中获取到的accesstoken。

        base_url = 'https://graph.qq.com/oauth2.0/me?'

        params = {
           'access_token': access_token
        }

        openid_url = base_url + urlencode(params)

        response = urlopen(openid_url)

        data = response.read().decode()

        print(data)

        try:
            dict = json.loads(data[10:-4])

        except Exception:
            raise Exception('数据获取失败')

        print(dict)

        openid = dict.get('openid')

        if openid is not None:

            return openid
